package com.wx.controller;

import com.alibaba.fastjson.JSON;
import com.bus.model.Authorize;
import com.bus.model.Config;
import com.bus.model.User;
import com.bus.service.ConfigService;
import com.bus.service.WxAuthorizeService;
import com.bus.service.WxUserService;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.SnsAccessToken;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.jfinal.weixin.sdk.api.SnsApi;
import com.jfinal.weixin.sdk.api.UserApi;
import com.wx.interceptor.ConfigInterceptor;
import com.wx.kit.URLCodeKit;

public class WeiXinOauthController extends Controller {
	static Log log = Log.getLog(WeiXinOauthController.class);
	static ConfigService srv = ConfigService.me;
	static WxUserService wxus = WxUserService.me;
	static WxAuthorizeService wxas = WxAuthorizeService.me;

	// 跳转到授权页面
	@Before(ConfigInterceptor.class)
	public void toOauth() {
		String rmid = getPara("rmid");// 再通过rmid 查询APPId,这里为了方便直接将其存入session
		Config config = (Config) getSession().getAttribute("config");
		if (null != config) {
			String appId = config.getAppId();
			// 通过appId查询配置的授权参数
			Authorize authorize = wxas.getByAppId(appId);
			if (null != authorize) {
				StringBuffer sbf = new StringBuffer();
				sbf.append(authorize.getDomain()).append("/oauth").append("/").append(rmid);
				String url = SnsAccessTokenApi.getAuthorizeURL(appId, sbf.toString(), authorize.getState(),
						authorize.getSnsapiBase() == 0 ? false : true);
				log.info("oauthUrl>" + url);
				redirect(url);
			} else {
				renderText("authorize is error.");
			}
		} else {
			renderText("config is error.");
		}
	}

	public void custom() {
		User user = (User) getSessionAttr("wxuser");
		setAttr("user", user);
		render("custom.html");
	}

	public void index() {
		int subscribe = 0;
		// 用户同意授权，获取code
		String code = getPara("code");
		String state = getPara("state");
		String rmid = getPara(0);
		// 通过rmid查询 公众号相关的配置
		Config config = srv.getConfigByRmid(rmid);
		if (null != config) {
			String appId = config.getAppId();
			String secret = ApiConfigKit.getApiConfig().getAppSecret();
			// 通过APPId查询授权配置信息
			Authorize authorize = wxas.getByAppId(appId);
			if (null != authorize) {
				String wxstate = authorize.getState();
				String redirectUri = authorize.getRedirectUri();
				String subscribeUrl = authorize.getSubscribeUrl();

				if (code != null) {
					// 通过code换取网页授权access_token
					SnsAccessToken snsAccessToken = SnsAccessTokenApi.getSnsAccessToken(appId, secret, code);
					String openId = snsAccessToken.getOpenid();
					// 拉取用户信息(需scope为 snsapi_userinfo) 无关注状态
					ApiResult snsuserInfo = SnsApi.getUserInfo(snsAccessToken.getAccessToken(), openId);
					ApiResult userInfo = null;
					if (StrKit.notBlank(subscribeUrl)) {
						// 可以获取到用户是否关注的状态 或者 通过openId查询已有的数据库来判断
						userInfo = UserApi.getUserInfo(openId);
						if (userInfo.isSucceed()) {
							subscribe = JSON.parseObject(userInfo.toString()).getIntValue("subscribe");
							log.info("is subscribe:" + subscribe);
						}
					}
					log.info("getUserInfo:" + snsuserInfo.getJson());
					if (snsuserInfo.isSucceed()) {
						User user = wxus.toSave(appId, snsuserInfo);
						if (null != user) {
							user.setNickName(URLCodeKit.decode(user.getNickName()));
							setSessionAttr("wxuser", user);
						}
					}
					if (subscribe == 0) {
						if (StrKit.notBlank(subscribeUrl)) {
							redirect(subscribeUrl);
						}
					} else {
						// 根据state 跳转到不同的页面
						if (state.equals(wxstate)) {
							redirect(redirectUri);
						} else {
							redirect("/");
						}
					}
				} else {
					renderText("code is  null");
				}
			}
		}
	}
}
